package com.longcheer.weibo;

import com.longcheer.weibo.util.WeiboConfig;
import com.longcheer.weibo.util.WeiboConstants;
import com.longcheer.weibo.vo.User;
import com.weibo.net.RequestToken;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

/**
 * 微博用户鉴权登录界面。
 * 
 * @author tufei
 *
 */
public class LoginActivity extends Activity {
    
    private static final String TAG = "PW_Login";
    public static User me;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        StartTask startTask = new StartTask();
        startTask.execute();
    }
    
    private boolean verify() {
        try {
            me = verifyUser(this);
            return true;
        } catch (WeiboException e) {
            Log.e(TAG, e.getMessage(), e);
            return false;
        }
    }
    
    private void startMain() {
        Intent intent = new Intent().setClass(this, MainActivity.class);
        intent.putExtra("authed", true);
        startActivity(intent);
    }
    
    private void startAuth() {
        Weibo weibo = Weibo.getInstance();
        try {
            
            RequestToken requestToken = weibo.getRequestToken(LoginActivity.this, Weibo.APP_KEY, 
                    Weibo.APP_SECRET, WeiboConstants.URL_ACTIVITY_CALLBACK);
            Log.i(TAG, "Request Token:" + requestToken.getToken());
            Log.i(TAG, "Request Secret:" + requestToken.getSecret());
            WeiboConfig.putRequestToken(this, requestToken);
            
            Uri uri = Uri.parse(Weibo.URL_AUTHENTICATION + "?display=wap2.0&oauth_token=" + 
                    requestToken.getToken() + "&from=xweibo");
            startActivity(new Intent(Intent.ACTION_VIEW, uri));
        }catch (WeiboException e){
            Log.e(TAG, "Get RequestToken error.", e);
        }
    }
    
    private void doStart() {
        WeiboConfig.readConfig(this);
        if (WeiboConfig.accessToken != null) {
            Weibo.getInstance().setAccessToken(WeiboConfig.accessToken);
            if (!verify()) {
                startAuth();
            } else {
                startMain();
            }
            
        } else {
            startAuth();
        }
        finish();   
    }
    
    public class StartTask extends AsyncTask<Integer, Integer, String> {

        @Override
        protected String doInBackground(Integer... params) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            doStart();
            return "OK";
        }
    }
    
    public User verifyUser(Context context) throws WeiboException {
        String url = WeiboConstants.API_SERVER + "account/verify_credentials.json";
        WeiboParameters bundle = new WeiboParameters();
        Weibo weibo = Weibo.getInstance();
        bundle.add("source", Weibo.APP_KEY);
        String resp = weibo.request(context, url, bundle, "GET", weibo.getAccessToken());
        
        try {
            JSONObject json = new JSONObject(resp);
            return new User(json);
        } catch (JSONException e) {
            throw new WeiboException(e.getMessage(), e);
        }
    }
}
